//
//  BaseNSObject.m
//  Pet
//
//  Created by karl on 2018/4/20.
//  Copyright © 2018年 karl. All rights reserved.
//

#import "BaseNSObject.h"
#import <objc/runtime.h>

#define ISNIL(a) ( ([[NSString stringWithFormat:@"%@",a] isEqualToString:@"<null>"])||([[NSString stringWithFormat:@"%@",a] isEqualToString:@"(null)"]) ? @"": [NSString stringWithFormat:@"%@",a])

@implementation BaseNSObject

+(NSObject*)DcodeClass:(Class)className withDict:(NSDictionary*)dict
{
    NSObject* result = [[className alloc] init];
    
    int i;
    unsigned int propertyCount = 0;
    objc_property_t *propertyList = class_copyPropertyList(className, &propertyCount);
    
    for ( i=0; i < propertyCount; i++ ) {
        objc_property_t *thisProperty = propertyList + i;
        const char* propertyName = property_getName(*thisProperty);
        
        const char* propertyAttributes = property_getAttributes(*thisProperty);
        
        if (NULL==strchr(propertyAttributes,'&')){
            //非retain的属性略过
            continue;
        }
        
        NSString *pname =  [[NSString alloc] initWithUTF8String:propertyName];
        
        [result setValue:ISNIL(dict[pname]) forKey:pname];
        
    }
    free(propertyList);
    
    return result;
}

//Model 到字典
+ (NSDictionary *)getDictWithObj:(id)obj
{
    NSMutableDictionary *props = [NSMutableDictionary dictionary];
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([obj class], &outCount);
    for (i = 0; i<outCount; i++)
    {
        objc_property_t property = properties[i];
        const char* char_f = property_getName(property);
        NSString *propertyName = [NSString stringWithUTF8String:char_f];
        id propertyValue = [obj valueForKey:(NSString *)propertyName];
        if (propertyValue) [props setObject:propertyValue forKey:propertyName];
    }
    free(properties);
    return props;
}


@end
